<template>
  <div>
    <Breadcrumb :items="['menu.system', 'menu.system.userManagement']" />
    <div>
      <a-spin :loading="pageLoading?.loading" style="width: 100%">
        <CardConponents v-if="ishavePermission(16, rolesStorage)">
          <a-button type="primary" @click="handleClick">新增</a-button>
        </CardConponents>
        <CardConponents>
          <a-table :data="dataList?.list">
            <template #columns>
              <a-table-column title="id" data-index="id"></a-table-column>
              <a-table-column title="角色名称" data-index="name"></a-table-column>
              <a-table-column title="状态" data-index="status">
                <template #cell="{ record }">
                  {{ showStatus(record) }}
                </template>
              </a-table-column>
              <a-table-column title="状态" data-index="status">
                <template #cell="{ record }">
                  {{ showIsAdmin(record) }}
                </template>
              </a-table-column>
              <a-table-column title="排序" data-index="sort"></a-table-column>
              <a-table-column title="创建时间" data-index="create_time"></a-table-column>
              <a-table-column title="操作">
                <template #cell="{ record }">
                  <a-button v-if="record?.is_admin !== 1" style="margin-right: 5px;" type="primary" size="small"
                    @click="editMenuBtn(record)">设置按钮权限</a-button>
                  <a-button style="margin-right: 5px;" type="primary" size="small"
                    v-if="ishavePermission(17, rolesStorage)" @click="handleEdidClick(record)">编辑</a-button>
                  <a-popconfirm content="确定要删除吗?" type="error" @ok=handleDelClick(record)>
                    <a-button type="primary" status="danger" size="small"
                      v-if="ishavePermission(22, rolesStorage)">删除</a-button>
                  </a-popconfirm>
                </template>
              </a-table-column>
            </template>
          </a-table>

        </CardConponents>
        <a-modal :maskClosable=false v-model:visible="visible" title="新增" :footer="false">
          <a-form :model="form" @submit="handleSubmit">
            <a-form-item field="Name" label="角色名称" :rules="[{ required: true, message: '不能为空' }]">
              <a-input v-model="form.Name" />
            </a-form-item>
            <a-form-item field="Sort" label="序号">
              <a-input v-model="form.Sort" />
            </a-form-item>
            <a-form-item field="StatusEd" label="状态">
              <a-switch :default-checked="true" v-model="form.StatusEd" />
            </a-form-item>
            <a-form-item field="IsAdmin" label="管理类型" :rules="[{ required: true, message: '不能为空' }]">
              <a-space direction="vertical" size="large">
                <a-radio-group v-model="form.IsAdmin">
                  <a-radio :value="1">超级管理员</a-radio>
                  <a-radio :value="0" :default-checked="true">普通管理员</a-radio>
                </a-radio-group>
              </a-space>
            </a-form-item>
            <div class="btn">
              <a-button style="width: 100px;margin-right: 10px;" @click="cancelClick">
                取消
              </a-button>
              <a-button style="width: 100px;" type="primary" html-type="submit" long :loading="loading">
                提交
              </a-button>
            </div>
          </a-form>
        </a-modal>
        <a-modal width="500" :maskClosable=false v-model:visible="setVisible" title="设置按钮权限" :footer="false">
          <div class="tree_box">
            <a-tree blockNode :checkable="true" :data="treeData" v-model:checked-keys="checkedKeys" />
          </div>
          <div class="btn">
            <a-button style="width: 100px;" type="primary" html-type="submit" long :loading="loading"
              @click="submitMenuBtn">
              提交
            </a-button>
          </div>
        </a-modal>
      </a-spin>
    </div>
  </div>
</template>


<script lang="ts" setup>
import CardConponents from '@/components/card/index.vue';
import { reactive, ref } from 'vue';
import useLoading from '@/hooks/loading';
import { Message } from '@arco-design/web-vue';
import { onMounted } from 'vue';
import { list, add, edit, del, menuList, menuRoleList, menuRoleAdd } from '@/api/role';
import { getRolesStorage, ishavePermission } from '@/utils/auth';

let rolesStorage: any = getRolesStorage();
const { loading, setLoading } = useLoading();

const dataList: any = reactive({
  list: [],
  total: 0
});
const pageLoading: any = reactive({ loading: false });
const visible = ref(false);
const setVisible = ref(false);

const treeData: any = ref([]);
const checkedKeys = ref([]);
const roleId: any = ref(null);
const form: any = reactive({
  Name: '',
  Sort: '',
  Status: '',
  IsAdmin: '',
  StatusEd: '',
  Id: '',
});

const cancelClick = () => {
  visible.value = false;
  form.Name = ''
  form.Sort = ''
  form.Status = ''
  form.IsAdmin = ''
  form.StatusEd = ''
  form.Id = ''
};

const getList = async () => {
  pageLoading.loading = true
  const res = await list({ data: { Offset: 0, Limit: 100 } })
  const ret = await menuList({})
  let newList: any = []
  if (ret?.data) {
    newList = ret.data.map((item: any) => processItem(item));
  }
  treeData.value = newList
  pageLoading.loading = false
  dataList.list = res?.data?.List
  dataList.total = res?.data?.Total
}

onMounted(() => {
  getList()
});

const showStatus = (value: any) => {
  return value.status === 1 ? '正常' : '禁止'
}


const showIsAdmin = (value: any) => {
  return value.is_admin === 1 ? '超管' : '普通管理'
}


const handleClick = () => {
  visible.value = true;
  form.Name = ''
  form.Sort = ''
  form.Status = ''
  form.IsAdmin = ''
  form.StatusEd = ''
  form.Id = ''
};



const handleSubmit = async ({ errors, values }: any) => {
  if (loading.value) return;
  if (!errors) {
    if (values.StatusEd == "true" || values.StatusEd == true) {
      values.Status = 1
    } else {
      values.Status = 0
    }
    try {

      if (form.Id > 0) {

        const res: any = await edit(values);
        Message.success(res?.msg);
        setLoading(false);

        if (res?.code == 1) {
          visible.value = false;
          getList()
        }
      } else {
        const res: any = await add(values);
        Message.success(res?.msg);
        setLoading(false);

        if (res?.code == 1) {
          visible.value = false;
          getList()
        }
      }
    } catch (error) {
      setLoading(false);
    }
  }
};


const handleEdidClick = (value: any) => {
  visible.value = true;
  form.Name = value.name
  form.IsAdmin = value.is_admin
  form.Sort = value.sort
  form.StatusEd = value.status == 1 ? true : false;
  form.Id = value.id
}

const processItem = (item: any) => {
  const newItem: any = {
    title: item?.name,
    key: item?.id,
    value: item?.id,
    children: item?.children ? item.children.map((child: any) => processItem(child)) : undefined
  };
  return newItem;
};

const editMenuBtn = async (value: any) => {
  roleId.value = value?.id
  const res = await menuRoleList({ RoleId: value?.id })
  const selectedKeys = res?.data?.map((item: any) => item?.menu_id) || []
  checkedKeys.value = selectedKeys
  setVisible.value = true
}

const submitMenuBtn = async () => {
  const MenuId = checkedKeys?.value.join(',') || ''
  const res: any = await menuRoleAdd({
    RoleId: roleId.value,
    MenuId
  })
  if (res?.code == 1) {
    Message.success('修改成功')
    setVisible.value = false
    checkedKeys.value = []
    roleId.value = null
    getList()
  }
}

// 删除
const handleDelClick = async (value: any) => {
  const res: any = await del({ Id: value?.id });
  if (res?.code === 1) {
    Message.success('删除成功')
    getList()
  }
}
</script>

<script lang="ts">
export default {
  name: 'RoleManagement'
};
</script>

<style lang="less" scoped>
.btn {
  display: flex;
  justify-content: flex-end;
}

.tree_box {
  max-height: 500px;
  overflow-y: auto;
}
</style>
